<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-09 16:34:16
 * @Last Modified time: 2023-02-20 11:07:07
 */

namespace app\api\controller\user;

use think\facade\App;
use app\common\services\store\OrderService;

/**
 * 用户订单管理
 * Class Order
 * @package app\api\controller\user
 */
class Order extends \app\api\controller\Base
{

    /**
     * OrderService constructor.
     * @param App $app
     */
    public function __construct(App $app,OrderService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }


    /**
     * 获取用户订单详细
     * @method(GET)
     */
    public function detail()
    {
        $id = $this->request->param('id');
        $detail = $this->service->getUserOrderDetail($id,$this->uid);
        $detail['is_allow_refund'] = $this->service->isAllowRefund($detail);
        $this->success('获取成功',[
            'order' => $detail
        ]);
    }

    /**
     * 申请取消订单
     * @method(PUT)
     */
    public function cancelOrder()
    {
        $id = $this->request->param('id');

        if ($this->service->cancelOrder([
            'order_id'=>$id,
            'user_id'=>$this->uid
        ])) {
            $this->success('申请取消成功');
        }
        $this->error($this->service->getError() ?: '申请取消失败');
    }

    /**
     * 我的订单列表
     * @method(GET)
     */
    public function list()
    {
        $dataType = $this->request->param('dataType');
        $list = $this->service->getUserList($this->uid, $dataType);
        return $this->success('获取成功',compact('list'));
    }

    /**
     * 立即支付
     * @method(GET)
     */
    public function pay()
    {
        $orderId = $this->request->param('id');
        $payType =  $this->request->param('pay_type');
        // 订单支付事件
        if (!$order = $this->service->onPay($orderId,$payType,$this->user)) {
            return $this->error($this->service->getError() ?: '订单支付失败');
        }
        // 构建微信支付请求
        $payment = $this->service->onPaymentByWechat($this->user,$payType,$order);
        // 支付状态提醒
        $this->success('获取成功',[
            'order_id' => $orderId,
            'payment' => $payment// 微信支付参数
        ]);
    }

    /**
     * 确定收货
     * @method(PUT)
     */
    public function receiptOrder(){
        $id = $this->request->param('id');

        if ($this->service->receiptOrder($id)) {
            $this->success('处理成功');
        }
        $this->error($this->service->getError() ?: '处理失败');
    }

}